package com.antg;

/**
 * @Description: Z 字形变换
 * @Author 子兔Antg
 * @Date 2021/11/15
 **/
public class Code_6 {
    public static void main(String[] args) {
        String s = "abcde";
        String convert = convert(s, 4);
        System.out.println(convert);
    }

    public static String convert(String s, int numRows) {
        if(numRows==1){
            return s;
        }
        //思路:使用一个二维矩阵来存储变换后的字符

        //1.计算二维矩阵的大小
        //1.1分别计算二维矩阵的宽高
        int high = numRows;
        int width;
        int unit = s.length()/(high+high-2);//有几个v单元
        int other = s.length()%(high+high-2);//剩余
        int unitWidth = unit*(high-1);
        int otherWidth = 0;
        if(other<=high){
            otherWidth = 1;
        }else{
            otherWidth = 1+other-high;
        }
        width = unitWidth+otherWidth;
        //1.2创建二维矩阵
        char[][] container = new char[high][width];

        //2.遍历字符串进行存储
        int under = 0;//向下走的坐标
        boolean underAble = true;//向下走的能力
        int top = high-1;//向上走的坐标
        boolean topRightAble = false;//向右上走的能力
        int right = 0;//向右走的坐标
        for(int i = 0;i<s.length();i++){
            //向下走
            if(underAble){
                container[under][right] = s.charAt(i);
                under++;
                if(under==high){
                    underAble = false;
                    topRightAble = true;
                    under = 0;
                }
            }
            //下右上走
            if(topRightAble){
                container[top][right] = s.charAt(i);
                top--;
                right++;
                if(top==0){
                    top = high-1;
                    topRightAble = false;
                    underAble = true;
                }
            }
        }
        StringBuilder res = new StringBuilder();
        //3.读取二维矩阵
        for(int i = 0;i<container.length;i++){
            for(int j = 0;j<container[i].length;j++){
                if(container[i][j]!= '\u0000'){
                    res.append(container[i][j]);
                }
            }
        }
        return res.toString();
    }
}
